package com.mezz.bones.im.gateway.handler;

import com.alibaba.fastjson.JSONException;
import com.mezz.bones.im.common.result.ImResultCode;
import com.mezz.bones.im.common.exception.ImBaseException;
import com.mezz.bones.im.common.result.ImResult;
import com.mezz.bones.im.gateway.util.ChannelUtil;
import io.netty.channel.*;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class NettyGlobalExceptionHandler extends ChannelInboundHandlerAdapter {

  @Override
  public void exceptionCaught(ChannelHandlerContext ctx, Throwable e) {

    log.debug("-----------NettyGlobalExceptionHandler begin-----------");

    log.error("netty exceptionCaught",e);

    if (e instanceof ImBaseException) {
      // 自定义业务异常，返回结果
      ImBaseException baseException = (ImBaseException) e;
      ImResult<?> errorResult = new ImResult<>();
      errorResult.setCode(baseException.getCode());
      errorResult.setErrmsg(baseException.getMessage());

      ImResult error = ImResult.errorMsg( baseException.getCode(), baseException.getMessage());
      if(errorResult.getData() != null){
        error.data(baseException.getData());
      }

      // 发送响应数据到客户端
      ctx.channel().writeAndFlush(error);
    } else if ( e instanceof JSONException) {

      ImResultCode errorCode = ImResultCode.SYS_ERROR;
      ImResult<?> result = ImResult.errorMsg(errorCode.getCode(),errorCode.getMessage());
      // 发送错误响应到客户端
      ctx.channel().writeAndFlush(result);

    } else {
      // 系统级别的错误
      ImResultCode errorCode = ImResultCode.SYS_ERROR;
      ImResult<?> result = ImResult.errorMsg(errorCode.getCode(),errorCode.getMessage());
      ChannelUtil.sendAndGracefullyClose(ctx,result);
    }

  }

}